<?php
class Model_MapperCommune implements Model_IMapper
{
	private $table = null;
	
	public function __construct($str_table, $pdo)
	{
		$this->table = new Model_TableCommune();
		$this->table->setConnexion($pdo);
		$this->table->init();
	}
	
	public function getAll($begin = null, $nb = null)
	{
                if(is_null($begin) && is_null($nb))
		{
			$lignes = $this->table->fetchAll();
		}
		else
		{
			$lignes = $this->table->fetchAllLimit($begin, $nb);
		}
                
		$results = array();
		foreach($lignes as $ligne)
		{
			$entity = new Model_Commune();
			$entity->setId_Commune($ligne['id_commune']);
			$entity->setNom($ligne['nom']);
			$entity->setCode_postal($ligne['code_postal']);
			$results[] = $entity;
		}
		return $results;
	}
	
	public function getOne($id)
	{
		$ligne = $this->table->fetchOne($id);
		if(!empty($ligne['id_commune']) && is_array($ligne) )
		{
			$entity = new Model_Commune();
			$entity->setId_commune($ligne['id_commune']);
			$entity->setNom($ligne['nom']);
			$entity->setCode_postal($ligne['code_postal']);
		}
		else 
		{
			$entity = null;
		}
		return $entity;
	}
	
	public function save(Model_IEntity $object)
	{
		if($object->getId_commune() == -1)
		{
			$id = $this->table->insert($object->getNom(), $object->getCode_postal());
			$object->setId_commune($id);
		}
		else
		{
			$this->table->update($object->getId_commune(), $object->getNom(), $object->getCode_postal());
		}
	}
	
	public function delete(Model_IEntity $object)
	{
		$this->table->delete($object->getId_commune());
	}
}